package com.uinnova.product.eam.mvc;

import com.binary.core.exception.BinaryException;
import com.binary.framework.web.RemoteResult;
import com.binary.jdbc.Page;
import com.uinnova.product.eam.base.cj.ResultMsg;
import com.uinnova.product.eam.comm.model.es.ArchReview;
import com.uinnova.product.eam.constant.ItemType;
import com.uinnova.product.eam.dto.SimpSystemInfo;
import com.uinnova.product.eam.feign.workable.FlowableFeign;
import com.uinnova.product.eam.feign.workable.entity.PorcessResponse;
import com.uinnova.product.eam.model.cj.domain.ChapterContext;
import com.uinnova.product.eam.model.cj.domain.PlanModuleAnnotationEntity;
import com.uinnova.product.eam.model.cj.group.AddGroup;
import com.uinnova.product.eam.model.cj.request.PlanModuleAnswerRequest;
import com.uinnova.product.eam.model.cj.vo.PlanChapterAnnotationVO;
import com.uinnova.product.eam.model.constants.FlowableConstant;
import com.uinnova.product.eam.model.es.ArchReviewInfo;
import com.uinnova.product.eam.model.vo.PlanModuleAnnotationReq;
import com.uinnova.product.eam.service.ArchReviewService;
import com.uinnova.product.eam.service.GTPlanModuleAnnotationService;
import com.uinnova.product.eam.service.cj.dao.ArchReviewDao;
import com.uinnova.product.eam.service.cj.dao.ChapterContextDao;
import com.uinnova.product.eam.service.cj.service.PlanModuleAnnotationService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/plan/annotation")
public class PlanModuleAnnotationMvc {

    @Resource
    private ChapterContextDao chapterContextDao;
    @Autowired
    private PlanModuleAnnotationService planModuleAnnotationService;
    @Autowired
    private ArchReviewDao archReviewDao;
    @Autowired
    private ArchReviewService archReviewService;
    @Autowired
    private FlowableFeign flowableFeign;
    @Resource
    private GTPlanModuleAnnotationService gtPlanModuleAnnotationService;

    @PostMapping("/saveAnswer")
    public RemoteResult saveAnswer(@RequestBody PlanModuleAnswerRequest request) {
        Assert.notNull(request, "批注回复参数不能为空");
        Assert.notNull(request.getId(), "批注主键不能为空");
        if (StringUtils.isBlank(request.getAnswer())) {
            throw new BinaryException("回复内容不能为空");
        }
        PlanModuleAnnotationEntity annotation = planModuleAnnotationService.getById(request.getId());
        if (annotation == null || Boolean.TRUE.equals(annotation.getDelFlag())) {
            throw new BinaryException("批注不存在");
        }
        if (Boolean.TRUE.equals(annotation.getProblem())) {
            throw new BinaryException("批注已归档为问题，不可以回复");
        }

        TermQueryBuilder query = QueryBuilders.termQuery("planIds", annotation.getPlanId());
        Page<ArchReview> page = archReviewDao.getSortListByQuery(1,1, query,"createTime", false);
        String bizKey = CollectionUtils.isEmpty(page.getData()) ? "" : page.getData().get(0).getId().toString();
        if (!StringUtils.isBlank(bizKey)) {
            PorcessResponse porcess = flowableFeign.getProcessInstanceByBusinessIdAndProcessDefinitionKey(bizKey, FlowableConstant.GT_TECHNICAL_SCHEME_APPROVE);
            if (porcess != null
                    && StringUtils.isNotBlank(porcess.getProcessInstanceId())
                    && StringUtils.isNotBlank(porcess.getProcessStartUserId())) {
                ArchReviewInfo info = archReviewService.getById(Long.valueOf(bizKey));
                String title = getTitle(info);
                request.setArchReviewName(title);
                request.setArchReviewId(info.getId());
                request.setProcessInstanceId(porcess.getProcessInstanceId());
                request.setProcessSubmitter(porcess.getProcessStartUserId());
            }
        }
        Long id = planModuleAnnotationService.saveAnswer(request);
        return new RemoteResult(id);
    }

    private String getTitle(ArchReviewInfo reviewInfo) {
        if (ItemType.PROJECT.equals(reviewInfo.getItemType())) {
            return reviewInfo.getProjectInfo().getLabel();
        }
        List<SimpSystemInfo> systemInfos = reviewInfo.getSystemInfos();
        String systemName = "";
        if (systemInfos.size() <= 5) {
            systemName = systemInfos.stream().map(SimpSystemInfo::getLabel).collect(Collectors.joining(","));
        } else {
            systemName = systemInfos.subList(0, 5).stream().map(SimpSystemInfo::getLabel)
                    .collect(Collectors.joining(",")).concat("等系统");
        }
        return systemName;
    }

    /**
     * 批注新增
     */
    @PostMapping("/save")
    public ResultMsg saveAnnotationWithNotice(@RequestBody @Validated(AddGroup.class) PlanModuleAnnotationReq annotationVo) {
        ChapterContext context = chapterContextDao.getById(annotationVo.getChapterId());
        Assert.notNull(context, "章节不存在");
        TermQueryBuilder query = QueryBuilders.termQuery("planIds", context.getPlanId());
        Page<ArchReview> page = archReviewDao.getSortListByQuery(1,1, query,"createTime", false);
        String bizKey = CollectionUtils.isEmpty(page.getData()) ? "" : page.getData().get(0).getId().toString();
        if (!StringUtils.isBlank(bizKey)) {
            PorcessResponse porcess = flowableFeign.getProcessInstanceByBusinessIdAndProcessDefinitionKey(bizKey, FlowableConstant.GT_TECHNICAL_SCHEME_APPROVE);
            if (porcess != null
                    && StringUtils.isNotBlank(porcess.getProcessInstanceId())
                    && StringUtils.isNotBlank(porcess.getProcessStartUserId())) {
                ArchReviewInfo info = archReviewService.getById(Long.valueOf(bizKey));
                String title = getTitle(info);
                annotationVo.setArchReviewName(title);
                annotationVo.setArchReviewId(info.getId());
                annotationVo.setProcessInstanceId(porcess.getProcessInstanceId());
                annotationVo.setProcessSubmitter(porcess.getProcessStartUserId());
            }
        }
        Long id = planModuleAnnotationService.saveAnnotationWithNotice(annotationVo);
        return new ResultMsg(id);
    }

    @PostMapping("/list")
    public ResultMsg list(@RequestBody PlanModuleAnswerRequest request) {
        Page<PlanChapterAnnotationVO> page = gtPlanModuleAnnotationService.findGTAnnotationList(request);
        return new ResultMsg(page);
    }

    @GetMapping("/closeCirculate/{circulateId}")
    public RemoteResult closeCirculate(@PathVariable Long circulateId) {
        return new RemoteResult(planModuleAnnotationService.closeCirculate(circulateId));
    }
}
